/*
 * @Author: hcluo
 * @Date: 2020-04-13 10:45:01
 * @LastEditors: hcluo
 * @LastEditTime: 2020-04-26 15:36:18
 * @Description: 政府项目
 */


export function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === variable) { return pair[1]; }
    }
    return null;
}
var host = getQueryVariable('host')

if (host === null) {
    // host = '',
    host = 'http://10.102.18.199:12204'
    /* IFDEBUG */
    // host: 'http://10.100.5.202:12202',
    // host = '10.100.7.61:12202'
    /* IFDEBUG */
}

var config = { host: host }
const getSession = () => {
    console.log('getSession')
    // url 获取session
    let session = getQueryVariable('wind.sessionid')
    if (session) return session

    //终端获取session
    if (window.external && window.external.ClientFunc) {
        var sessionId = window.external.ClientFunc(JSON.stringify({ "func": "querydata", "isGlobal": "1", "name": "sessionid" }))
        return JSON.parse(sessionId).value
    }

    //开发使用session
    return 'f36e5866181f43dea13c1c1bb478f96d'
}

export const sessionId = getSession();
export const enterprisesServer = "/govwebapi/gov/web/api/integration/dataset/datainfo";

export { config }

export const request = ({ url, method = 'POST', params, body }) => {
    let opt = {
        method,
        headers: {
            'Content-Type': 'application/json',
            // 'right': '4C203DE15'
        },
    };

    url += '?wind.sessionid=' + sessionId

    if (body) {
        opt.body = JSON.stringify(body)
    }

    if (params) {

        for (const key in params) {
            url += `&${key}=${JSON.stringify(params[key])}`
        }
    }

    // const doRequest = new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //         reject('mock network err');
    //     }, 1000)
    // })

    // return doRequest
    return fetch(config.host + url, opt).then((response) => {
        if (!response.ok) {
            return Promise.reject(response.status);
        }
        return response.json();
    }).then((res) => {
        if (res.resultCode === '200') {
            return res.resultData;
        } else if (res.resultCode === '403') {
            window.location.href = './403.html'
        } else {
            console.error('服务端错误：', config.host + url, res)
            return Promise.reject(res.resultMessage);
        }
    })

};

